package com.ocn.li.scmdy.modules.app.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.ocn.li.scmdy.common.utils.QueryExt;
import com.ocn.li.scmdy.common.utils.R;
import com.ocn.li.scmdy.common.utils.RedisUtils;
import com.ocn.li.scmdy.common.validator.ValidatorUtils;
import com.ocn.li.scmdy.config.DemoConfig;
import com.ocn.li.scmdy.config.QcloudConfig;
import com.ocn.li.scmdy.modules.app.annotation.Login;
import com.ocn.li.scmdy.modules.app.entity.BasicPopulationBase;
import com.ocn.li.scmdy.modules.app.form.AdApkFrom;
import com.ocn.li.scmdy.modules.app.form.BasicPopulationBaseSaveForm;
import com.ocn.li.scmdy.modules.app.form.HzFrom;
import com.ocn.li.scmdy.modules.app.service.BasicPopulationBaseService;
import com.ocn.li.scmdy.modules.app.service.DyUserService;
import com.ocn.li.scmdy.modules.cache.DyConstant;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.*;

/**
 * @ClassName ApiDemoController
 * @Description 各类操作接口demo
 * @Author Li9527
 * @Date 2020/9/18 8:51
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/demo")
@Api(value = "ApiDemoController", tags = {"移动端--各类操作接口demo"})
public class ApiDemoController {

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    DemoConfig demoConfig;

    @Autowired
    BasicPopulationBaseService populationBaseService;

    @Autowired
    DyUserService dyUserService;

    @Autowired
    QcloudConfig qcloudConfig;

    /**
     * @Author Li9527
     * @Description  单文件上传
     * @Date  2020-9-18 8:55
     * @Param [file]
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @PostMapping("/upload")
    @ApiOperation("单文件上传")
    public R upload(@RequestParam("file") MultipartFile file){
        // 获取MultipartFile文件信息(注意参数为前端对应的参数名称) 并随机文件名
        String fileName = UUID.randomUUID().toString() + file.getOriginalFilename()
                .substring(file.getOriginalFilename().lastIndexOf("."));
        // 存储路径可在配置文件中指定
        File pfile = new File(demoConfig.getDemo_path());
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        File file2 = new File(pfile,  fileName);
        try {
            //使用此方法保存必须要绝对路径且文件夹必须已存在,否则报错
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error( "上传失败");
        }
        return R.ok("上传成功").put("data", "/upload/" + fileName);
    }


    /**
     * @Author Li9527
     * @Description  文件同表单数据一起上传
     * @Date  2020-9-18 8:55
     * @Param [file]
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @PostMapping("/uploadForm")
    @ApiOperation("文件同表单数据一起上传")
    public R uploadForm(@RequestParam("file")MultipartFile file, AdApkFrom from){
        System.out.println("文件是否丢失？" + file + "---------form表单数据是否丢失？" + from);
        String fileName = file.getOriginalFilename();
        // 存储路径可在配置文件中指定
        File pfile = new File(demoConfig.getDemo_path());
        if (!pfile.exists()) {
            pfile.mkdirs();
        }
        File file2 = new File(pfile,  fileName);
        try {
            //使用此方法保存必须要绝对路径且文件夹必须已存在,否则报错
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error( "上传失败");
        }
        return R.ok("上传成功").put("data", "/upload/" + fileName);
    }

    /**
     * @Author Li9527
     * @Description  交互redis/增删改查
     * @Date  2020-9-18 8:55
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @PostMapping("/testRedis")
    @ApiOperation(" 交互redis/增删改查")
    public R testRedis(){
        Map<Object, Object> map = redisUtils.getMap(DyConstant.RedisKey.MOBILE_EXTEND_ATTRIBUTE_JSON);
        Map<String, String> newMap = redisUtils.mapConvert(map);
        System.out.println("查找成功");
        redisUtils.put(DyConstant.RedisKey.MOBILE_EXTEND_ATTRIBUTE_JSON,"测试key","测试json");
        System.out.println("插入成功");
        redisUtils.put(DyConstant.RedisKey.MOBILE_EXTEND_ATTRIBUTE_JSON,"测试key","新的value");
        System.out.println("修改成功");
        Object o = redisUtils.getValueOfMap(DyConstant.RedisKey.MOBILE_EXTEND_ATTRIBUTE_JSON,"测试key");
        System.out.println("获取单独key成功" + o);
        redisUtils.removeFromMap(DyConstant.RedisKey.MOBILE_EXTEND_ATTRIBUTE_JSON,"测试key");
        System.out.println("删除成功");
        return R.ok("返回配置文件成功").put("data",newMap);
    }

    /**
     * @Author Li9527
     * @Description  testTables
     * @Date  10:31
     * @Param [BasicPopulationBaseSaveForm]
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @PostMapping("/testTables")
    @ApiOperation(" 交互单表/增删改查")
    public R testTables(@RequestBody BasicPopulationBaseSaveForm form){
        System.out.println("输出接到的对象,开始操作--" + form);
        // 校验
        ValidatorUtils.validateEntity(form);
        // 注入
        BasicPopulationBase basicPopulationBase = new BasicPopulationBase();
        BeanUtils.copyProperties(form,basicPopulationBase);
        basicPopulationBase.setCreateTime(new Date());
        // 新增
        Boolean cflag = populationBaseService.insert(basicPopulationBase);
        if(cflag){
            System.out.println("新增成功");
        }
        // 查找
        BasicPopulationBase populationBase = populationBaseService.selectById(basicPopulationBase.getId_());
        // 可加条件
        BasicPopulationBase onePopulationBase = populationBaseService.selectOne(new EntityWrapper<BasicPopulationBase>().
                eq("ID_NUMBER",basicPopulationBase.getIdNumber()));
        // 编辑 修改身份证号和工作
        onePopulationBase.setIdNumber("430111TestUpdateNum");
        onePopulationBase.setPolitical("团员");
        onePopulationBase.setUpdateTime(new Date());
        Boolean uflag = populationBaseService.updateById(onePopulationBase);
        if(uflag){
            System.out.println("修改成功");
        }
        // 逻辑删除可以修改delflag = 1 即可
        Boolean dflag = populationBaseService.deleteById(onePopulationBase.getId_());
        if(dflag){
            System.out.println("删除成功");
        }
        return R.ok("操作单表结束");
    }


    /**
     * @Author Li9527
     * @Description  testPage
     * @Date 2020/9/18 11:04
     * @Param [params]
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @GetMapping("/testPage")
    @ApiOperation(" 手写sql分页查询/条件")
    public R testPage(@RequestParam Map<String, Object> params){
        params.put("orderByField", "u.create_time");
        params.put("isAsc", false);
        Page page = dyUserService.selectPageUser(new QueryExt(params));
        return R.ok().put("data",page);
    }

    /**
     * @Author Li9527
     * @Description  jwtToken直接捕获用户信息/参数直接体现，无需客户端再传该用户的用户id，区划之类信息
     * @Date  2020-9-18 15:09:56
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @Login
    @GetMapping("/testJwtToken")
    @ApiOperation("jwtToken直接捕获用户信息")
    public R testJwtToken(@ApiIgnore @RequestAttribute(value = "accountId") String accountId,
                          @ApiIgnore @RequestAttribute(value = "accountName") String accountName,
                          @ApiIgnore @RequestAttribute(value = "dataAreaCode") String dataAreaCode){
        Map<String,Object> map = new HashMap<>();
        map.put("accountId",accountId);
        map.put("accountName",accountName);
        map.put("dataAreaCode",dataAreaCode);
        return R.ok("捕获成功").put("data",map);
    }


    /**
     * @Author Li9527
     * @Description  sendHzLogin
     * @Date 2020/11/19 12:43
     * @Param [from]
     * @return com.ocn.li.scmdy.common.utils.R
     **/
    @PostMapping("/sendHzLogin")
    @ApiOperation("演示慧正登陆接口调用 解决跨域")
    public R sendHzLogin(@RequestBody HzFrom from){
        // 定义慧正接口地址
        String url = "http://10.10.29.222:1204/horizon-workflow-web/horizon/workflow/rest/user/login.wf";
        HttpRequest request = HttpUtil.createPost(url);
        //转化成json对象
        String jsonResult = JSONObject.toJSONString(from);
        request.body(jsonResult);
        JSONObject responseJson = null;
        HttpResponse response = request.execute();
        if(response.getStatus() == 200){
            String body = response.body();
            System.out.println(body);
            responseJson = JSONObject.parseObject(body);
        }
        return R.ok().put("data",responseJson);
    }



    /**
     * 本地图片转换Base64的方法
     *
     * @param imgPath
     */

    private static String ImageToBase64(String imgPath) {
        byte[] data = null;
        // 读取图片字节数组
        try {
            InputStream in = new FileInputStream(imgPath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        // 返回Base64编码过的字节数组字符串
        String img64 = encoder.encode(Objects.requireNonNull(data));
        return img64;
    }

}
